#include "stm32f10x.h"
#include "FreeRTOS.h"
#include "task.h"
#include "config.h"
#include "var.h"
#include "queue.h"
#include "semphr.h"
#include "sim900.h"
#include "common.h"
#include "serial.h"

uint32_t timeOut_1byte = 0;

void USART_SendString(USART_TypeDef* usart,char* data)
{
  if(xSemaphoreTake(xSem_pc_usart,portMAX_DELAY) == pdTRUE)
  {
    while(*data != '\0')
    {	
      while(USART_GetFlagStatus(usart, USART_FLAG_TXE) == RESET){;}
      USART_SendData(usart,*data);
      data++;
    }	
    xSemaphoreGive(xSem_pc_usart);
  }	
			
}
void USART_SendByteArray(USART_TypeDef* usart,char* data, uint32_t length)
{
	uint32_t i = 0;
	for(i = 0; i < length; i++)
	{
		while(USART_GetFlagStatus(usart, USART_FLAG_TXE) == RESET){;}
		USART_SendData(usart,*data);	
		data++;
	}				
}
// send 1 array byte that have length elements 
//void USART_SendByteArray(USART_TypeDef* usart,char* data, uint32_t length)
//{
//	uint32_t i = 0;
//	for(i = 0; i < length; i++)
//	{
//		while(USART_GetFlagStatus(usart, USART_FLAG_TXE) == RESET){;}
//		USART_SendData(usart,*data);	
//		data++;
//	}
//}
// send 1 byte via USART
void USART_SendByte(USART_TypeDef* usart,uint8_t data)
{
    while(USART_GetFlagStatus(usart, USART_FLAG_TXE) == RESET){;}
    USART_SendData(usart,data);	
}
// timeOut(ms). 
USART_Error USART_ReceiveByte(USART_TypeDef* usart, uint8_t *c, uint32_t timeOut)
{
	timeOut_1byte = timeOut;
	//timeOut_1byte-- trong exception cua SysTick Timer
	while(USART_GetFlagStatus(usart, USART_FLAG_RXNE) == RESET && timeOut_1byte);
	if(timeOut_1byte)
		*c = USART_ReceiveData(usart);
	else
		return TIME_OUT;
	return NO_ERR;
}
// disable an interrupt
void USART_DisableInterrupt(USART_TypeDef* usart,USART_Interrupt it)
{
	if(it == RX_IT)
	{
		USART_ITConfig(usart, USART_IT_RXNE, DISABLE);
	}
	else if(it == TX_IT)
	{
		USART_ITConfig(usart, USART_IT_TXE, DISABLE);
	}
}
// enable an interrupt
void USART_EnableInterrupt(USART_TypeDef* usart,USART_Interrupt it)
{
		if(it == RX_IT)
	{
		USART_ITConfig(usart, USART_IT_RXNE, ENABLE);
	}
	else if(it == TX_IT)
	{
		USART_ITConfig(usart, USART_IT_TXE, ENABLE);
	}
}
